package com.holdtime.jtt809dataservice.client.event;

import com.edata.common.BytesUtil;
import com.holdtime.jtt809dataservice.common.event.MessageReceiveEvent;
import com.holdtime.jtt809dataservice.common.process.TransmitProtocolProcessor;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 *  author: sunwei
 *  Date: 2025/3/23 00:20
 *  Description:
 */
@Slf4j
@Component
public class TransmitMessageEventListener {
    @Autowired
    private List<TransmitProtocolProcessor> processorList;

    private Map<Integer, TransmitProtocolProcessor> processorMap;

    @PostConstruct
    public void init() {
        processorMap = processorList.stream().collect(Collectors.toMap(TransmitProtocolProcessor::getMsgID, Function.identity()));
    }

    /**
     * 异步事件处理
     */
    @EventListener
    @Async("myAsync")
    public void onEvent(MessageReceiveEvent event) {
        TransmitProtocolProcessor processor = processorMap.get(event.getMsgID());
        if (processor == null) {
            log.info(String.format("没有找到消息类型：0x%s 所对应的处理器。", BytesUtil.toHexString(event.getMsgID(), 4)));
            return;
        }
        processor.process(event);
    }
}
